package org.nobject.common.net;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Enumeration;

import org.nobject.common.file.FileUtils;

/**
 * URLUtils
 *
 * @author bianrongjun
 * @version 1.0
 */
public class URLUtils {
	
	public static void main(String[] args) {
		String s=FileUtils.read2String("c:/a.txt");
		System.out.println(encode(s));
	}
	
	/** 
	 * 解码
	 * @param str 字符串
	 */
	public static String decode(String str){
		return decode(str,"utf-8");
	}
	
	/** 
	 * 解码
	 * @param str 字符串
	 * @param charset 字符集
	 */
	public static String decode(String str,String charset){
		try {
			return java.net.URLDecoder.decode(str,charset);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}
	
	/** 
	 * 编码
	 * @param str
	 */
	public static String encode(String str){
		//.replace(/!/g, "%21").replace(/'/g, "%27").replace(/\(/g, "%28").replace(/\)/g, "%29").replace(/~/g, "%7E")
		
		try {
			str=URLEncoder.encode(str,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
		
		str=str	.replaceAll("\\!"	,"%21")
				.replaceAll("'"		,"%27")
				.replaceAll("\\("	,"%28")
				.replaceAll("\\)"	,"%29")
				.replaceAll("\\~"	,"%7E");
		return str;
	}
	
	/** 
	 * 获取URL
	 * @param resName
	 */
	public static URL getURL(String resName){
		try {
			Enumeration e=Thread.currentThread().getContextClassLoader().getResources(resName);
			if(e.hasMoreElements()) return (URL)e.nextElement();
			return null;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
//	public static void main(String[] args) {
//		System.out.println(getURL("java/lang/String.class"));
//		System.out.println(getURL("org/nobject/common/lang/ThreadUtils.class"));
//	}
}
